package com.sumainfor.pc.gmio.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.fabric.xmlrpc.base.Params;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.RatesMapper;
import com.sumainfor.pc.gmio.feign.BaseFeignZuul;
import com.sumainfor.pc.gmio.feign.BasePcMktFeign;
import com.sumainfor.pc.gmio.service.RatesService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Jack Chen
 * @Create 2019-01-23 17:52
 * 各地区收费标准
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class RatesServiceImpl implements RatesService {

    @Autowired
    private RatesMapper ratesMapper;

    @Autowired
    private BaseFeignZuul feignZuul;


    @Autowired
    private BasePcMktFeign mktFeign;

    /**
     * 获得所有收费标准数据列表
     *
     * @return
     */
    @Override
    public JsonResult getDataList() {
        return JsonResult.success(ratesMapper.selectDataList());
    }

    /**
     * 获得公司数据
     *
     * @param page
     * @return
     */
    @Override
    public JsonResult getGosList(Page page) {
        if (page.getSize() < 0) {
            page.setSize(Integer.MAX_VALUE);
            page.setCurrent(1);
        }
        CustomMap params = CustomMap.create("size", page.getSize()).put("current", page.getCurrent());
        Page<Map<String, Object>> list = feignZuul.selectGosList(params);
        return JsonResult.success(list);
    }


    /**
     * 城市下： 下拉框数据 获得城市数据
     *
     * @return
     */
    @Override
    public JsonResult getLevelCityForSpinner(Page page) {
        if (page.getSize() < 0) {
            page.setSize(Integer.MAX_VALUE);
            page.setCurrent(1);
        }
        CustomMap params = CustomMap.create("size", page.getSize()).put("current", page.getCurrent());
        Page<Map<String, Object>> cityListAll = feignZuul.getCityListAll(params);
        return JsonResult.success(cityListAll);
    }

    /**
     * 服务中心： 服务中心 下拉框数据 选择城市 / 选择服务中心
     * @param cityId 城市编号
     * @param page
     * @return
     */
    @Override
    public JsonResult getLevelServerCenterForSpinner(Page page, String cityId) {
        if (page.getSize() < 0) {
            page.setSize(Integer.MAX_VALUE);
            page.setCurrent(1);
        }
        CustomMap params = CustomMap.create("size", page.getSize()).put("current", page.getCurrent());
        params.put("cityId", cityId);
        Page<Map<String, Object>> dataList = feignZuul.getCenterByCityId(params);
        return JsonResult.success(dataList);
    }


    /**
     * 查询小区数据 根据服务中心的编号
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public JsonResult selectProjectListView(Page page, Map<String, Object> params) {
        if (page.getSize() < 0) {
            page.setSize(Integer.MAX_VALUE);
            page.setCurrent(1);
        }
        //城市编号
        Integer centerId = MapUtils.getInteger(params, "centerId");
        CustomMap map = CustomMap.create("size", page.getSize()).put("current", page.getCurrent());
        map.put("centerId", centerId);
        //查询小区项目
        Page<Map<String, Object>> project = mktFeign.selectProjectByCenterId(map);
        return JsonResult.success(project);
    }


    /**
     * 查询小区数据的所有的房源信息
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public JsonResult selectHousingListView(Page page, Map<String, Object> params) {
        //查询小区内的所有房源
        CustomMap map = CustomMap.create("size", page.getSize()).put("current", page.getCurrent());
        map.putAll(params);
        Page<Map<String, Object>> view = mktFeign.selectHousingListView(map);
        view.setRecords(view.getRecords().stream().map(item -> {
            item.put("Type", MapUtils.getIntValue(item, "IfOperaType") == 0 ? "合租" : "整租");
            return item;
        }).collect(Collectors.toList()));
        return JsonResult.success(view);
    }

    /**
     * 添加数据 收费标准
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult addData(Map<String, Object> params) {
        String chaId = MapUtils.getString(params, "ChaId");
        if (StringUtils.isNotBlank(chaId)) {
            JsonResult result = deleteRatesById(chaId);
            if (!result.isSuccess()) {
                return JsonResult.error("删除失败 1");
            }
        } else {
            chaId = UUIDUtils.generatePrefixUuid("CHA-");
        }
        params.put("ChaId", chaId);
        List<Map<String, Object>> dataList = (List<Map<String, Object>>) MapUtils.getObject(params, "dataList");
        if (CollectionUtils.isEmpty(dataList)) {
            return JsonResult.errorForEmpty();
        }
        params.remove("dataList");
        //添加主表数据
        ParamsCommon.commonInsertParms(params, getClass());
        int row = ratesMapper.insertMain(params);
        if (row <= 0) {
            throw new TCException("添加数据失败");
        }
        for (Map<String, Object> map : dataList) {
            map.put("ChaId", chaId);
            String[] keys = {"ChaType", "ContactId"};
            if (!FieldCheckUtil.isMapFieldNotNull(map, keys)) {
                throw new TCException("DataList Item 参数不完整");
            }
            ParamsCommon.commonInsertParms(map, getClass());
            row = ratesMapper.insertInfoData(map);
            if (row <= 0) {
                throw new TCException("添加数据失败");
            }
        }
        return JsonResult.actionSuccess();
    }


    /**
     * 删除一个收费标准
     *
     * @param chaId
     * @return
     */
    @Override
    public JsonResult deleteRatesById(String chaId) {
        int row = ratesMapper.deleteChargesMain(chaId);
        if (row > 0) {
            row = ratesMapper.deleteChargesInfo(chaId);
        }
        if (row <= 0) {
            throw new TCException("删除失败");
        }
        return JsonResult.actionSuccess();
    }


//    /**
//     * 获取收费标准数据
//     *
//     * @param chaId
//     * @return
//     */
//    @Override
//    public JsonResult getRatesDataInfo(String chaId) {
//        //获取主表数据
//        Map<String, Object> ratesMain = ratesMapper.getRatesMain(chaId);
//        if (MapUtils.isEmpty(ratesMain)) {
//            return JsonResult.error("数据不存在");
//        }
//        //获取详表数据
//        List<Map<String, Object>> infoList = ratesMapper.selectRatesInfoList(chaId);
//        for (Map<String, Object> map : infoList) {
//            Integer type = MapUtils.getInteger(map, "ChaType");
//            String id = MapUtils.getString(map, "ContactId");
//            map.put("dataMap", mktFeign.selectHousingForType(2, id));
//
//
////            switch (type) {
////                case 1:
////                    map.put("dataMap", feignZuul.getDataByTypeAndId(id, 1));
////                    break;
////                case 2:
////                    map.put("dataMap", feignZuul.getDataByTypeAndId(id, 2));
////                    break;
////                case 3:
////                    map.put("dataMap", feignZuul.getDataByTypeAndId(id, 3));
////                    break;
////                case 4:
////                    //项目
////                    map.put("dataMap", mktFeign.selectHousingForType(1, id));
////                    break;
////                case 5:
////                    //房源
////                    map.put("dataMap", mktFeign.selectHousingForType(2, id));
////                    break;
////                default:
////                    throw new TCException("未知的类型");
////            }
//        }
//        CustomMap data = CustomMap.create("main", ratesMain)
//                .put("list", infoList);
//        if (CollectionUtils.isNotEmpty(infoList)) {
//            data.put("type", infoList.get(0).get("ChaType"));
//        }
//        return JsonResult.success(data);
//    }



    /**
     * 获取收费标准数据
     *
     * @param chaId
     * @return
     */
    @Override
    public JsonResult getRatesDataInfo(String chaId) {
        //获取主表数据
        Map<String, Object> ratesMain = ratesMapper.getRatesMain(chaId);
        if (MapUtils.isEmpty(ratesMain)) {
            return JsonResult.error("数据不存在");
        }
        //获取详表数据
        List<Map<String, Object>> infoList = ratesMapper.selectRatesInfoList(chaId);
        List<String> HouInfoIdList = new ArrayList<>();
        if (infoList.size()>0){
         for (Map<String,Object> map1:infoList){
             HouInfoIdList.add(map1.get("ContactId").toString());
         }
        }
        if (HouInfoIdList.size()>0){
            Map<String,Object> params = new HashMap<>();
            params.put("HouInfoIdList",HouInfoIdList);
             List<Map<String,Object>> map2 = mktFeign.getHousingInfoByIdsss(params);
             for (Map<String,Object> map0ne :infoList){
                 for (Map<String,Object> mapTwo:map2){
                     if (map0ne.get("ContactId").toString().equals(mapTwo.get("HouInfoId").toString())){
                         map0ne.putAll(mapTwo);
                     }
                 }
             }

        }

        CustomMap data = CustomMap.create("main", ratesMain)
                .put("list", infoList);
        if (CollectionUtils.isNotEmpty(infoList)) {
            data.put("type", infoList.get(0).get("ChaType"));
        }
        return JsonResult.success(data);
    }

}
